# -*- coding: utf-8 -*-
"""
Created on Mon Feb  6 11:17:44 2023

@author: shangfr
"""
import openai
import streamlit as st
from streamlit_chat import message
from PIL import Image


st.set_page_config(
    page_title = "ChatGPT chatbot",
    page_icon = Image.open("favicon.png")
)

st.markdown("""
<style>
.stTextInput > label {
font-size:120%;
font-weight:bold;
color:white;
background:#00a6ac;
border: 2px;
border-radius: 3px;
}


</style>
""", unsafe_allow_html=True)

if 'generated' not in st.session_state:
    st.session_state['generated'] = []

if 'past' not in st.session_state:
    st.session_state['past'] = []

if 'user_input' not in st.session_state:
    st.session_state['user_input'] = ""


openai.api_key = st.secrets['api_key']

@st.cache(persist=True,allow_output_mutation=True,show_spinner=False,suppress_st_warning=True)
def answer_ChatGPT(question):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=question,
        temperature=0,
        max_tokens=300,
        top_p=1,
        frequency_penalty=0.0,
        presence_penalty=0.0,
    )
    return response.choices[0].text

    
def input_and_clear():
    st.session_state['user_input'] = st.session_state['input']
    st.session_state['input'] = ""

# layout
st.header("🔬 ChatGPT Demo")

if st.session_state['user_input']:
    try:
        output = answer_ChatGPT(st.session_state['user_input'])
    except:
        output = 'error'
    st.session_state.past.append(st.session_state['user_input'])
    st.session_state.generated.append(output)

if st.session_state['generated']:
    for i in range(len(st.session_state['generated'])):
        st.info(st.session_state['past'][i], icon="🤶")
        ans = st.session_state["generated"][i]
        if ans == 'error':
            st.error('网络错误，请再试一遍。', icon="🤖")
            st.session_state["generated"].pop(i)
            st.session_state['past'].pop(i)
        else:
            st.success(ans, icon="🤖")

st.text_input("**请输入问题 👇**", key="input", on_change=input_and_clear)
